from PyQt4 import QtCore, QtGui

class ListWidget(QtGui.QListWidget):
  def __init__(self):
    QtGui.QListWidget.__init__(self)
    self.ctrl_pressed = False
    self.zoom_step = 1
    self.view_type = 0
    self.min_icon_size = QtCore.QSize(10, 10)

  def show_list_view(self):
    self.setViewMode(QtGui.QListView.ListMode)
    self.setGridSize(self.iconSize())

  def show_grid_view(self):
    self.setViewMode(QtGui.QListView.IconMode)
    size = self.iconSize()
    self.setGridSize(QtCore.QSize(size.width() + 10, size.height() + 10))
    print('w: %d, h: %d' % (size.width(), size.height()))

  def toggle_view(self):
    self.view_type = 1 - self.view_type
    self.update_view()
    self.setFocus(QtCore.Qt.OtherFocusReason)

  def update_view(self):
    if self.view_type == 0:
      self.show_list_view()
    else:
      self.show_grid_view()

  def setIconSize(self, size):
    if (size.width() < self.min_icon_size.width() or
        size.height() < self.min_icon_size.height()) :
      return
    QtGui.QListWidget.setIconSize(self, size)
    self.update_view()

  def wheelEvent(self, event):
    if self.ctrl_pressed:
      n_steps = event.delta() / 8
      size = self.iconSize();
      step = n_steps * self.zoom_step
      self.setIconSize(QtCore.QSize(size.width() + step, size.height() + step))
      print('step:%d' % step)
    else:
      QtGui.QListWidget.wheelEvent(self, event)

  def keyPressEvent(self, event):
    if event.key() == QtCore.Qt.Key_Control:
      self.ctrl_pressed = True
      print('ctrl pressed')
    QtGui.QListWidget.keyPressEvent(self, event)

  def keyReleaseEvent(self, event):
    if event.key() == QtCore.Qt.Key_Control:
      self.ctrl_pressed = False
      print('ctrl released')
    QtGui.QListWidget.keyReleaseEvent(self, event)

